package com.ima.web.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ima.web.beans.db.Categories;
import com.ima.web.beans.db.SubCategories;
import com.ima.web.dao.SubCategoriesDao;
import com.ima.web.dao.UsersDao;

@Repository
public class SubCategoriesDaoImpl implements SubCategoriesDao {

	private SessionFactory sessionFactory;
	private UsersDao usersDao; 
	
	@Autowired
	public void setDependencies(SessionFactory sessionFactory,UsersDao usersDao){
		this.sessionFactory = sessionFactory;
		this.usersDao = usersDao;
	}
	
	@Override
	public void save(SubCategories data) {
		Session s = sessionFactory.getCurrentSession();
		s.save(data);

	}

	@Override
	public void delete(SubCategories data) {
		// TODO Auto-generated method stub

	}

	@Override
	public List<SubCategories> list(SubCategories data) {
		Session s = sessionFactory.getCurrentSession();
		Criteria c = s.createCriteria(SubCategories.class);
		c.add(Example.create(data));
		
		if(data.getApprover()!=null){
			//c.createCriteria("approver").add(Example.create(data.getApprover()));
			c.createCriteria("approver", JoinType.INNER_JOIN).add(Example.create(data.getApprover()));
		}
			
		List<SubCategories> cats = c.list();

		return cats;
	}

	@Override
	public SubCategories findById(int id) {
		Session s = sessionFactory.getCurrentSession();
		
		SubCategories scat = (SubCategories)s.load(SubCategories.class, id); 

		System.out.println("subcategories findbyid: "+scat.getName());
		s.update(scat);
		return scat;
	}

	@Override
	public List<SubCategories> getToBeApproved() {
		Session s = sessionFactory.getCurrentSession();
		Criteria c = s.createCriteria(SubCategories.class);
		
		c.add(Restrictions.isNull("approver"));
		c.add(Restrictions.isNull("approvedDate"));
		c.add(Restrictions.eq("deleted", false));
		c.add(Restrictions.eq("approved", false));
		
		return c.list();
	}

	@Override
	public List<SubCategories> getApprovedByUser(String username) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SubCategories> getApprovedByUser(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SubCategories> getApproved() {
		Session s = sessionFactory.getCurrentSession();
		Criteria c = s.createCriteria(SubCategories.class);
		
		c.add(Restrictions.isNotNull("approver"));
		c.add(Restrictions.isNotNull("approvedDate"));
		c.add(Restrictions.eq("deleted", false));
		c.add(Restrictions.eq("approved",true));
		
		return c.list();
	}

}
